const { DataTypes } = require('sequelize')
const sequelize = require('../config/database')

const Role = sequelize.define('Role', {
  id: {
    type: DataTypes.INTEGER,
    primaryKey: true,
    autoIncrement: true,
    comment: '角色ID'
  },
  name: {
    type: DataTypes.STRING(50),
    allowNull: false,
    comment: '角色名称'
  },
  code: {
    type: DataTypes.STRING(50),
    allowNull: false,
    unique: true,
    comment: '角色编码'
  },
  description: {
    type: DataTypes.STRING(200),
    allowNull: true,
    comment: '角色描述'
  },
  status: {
    type: DataTypes.TINYINT,
    allowNull: false,
    defaultValue: 1,
    comment: '状态（1正常 0停用）'
  }
}, {
  tableName: 'roles',
  timestamps: true,
  indexes: [
    {
      unique: true,
      fields: ['code']
    }
  ]
})

// 创建系统预设角色
Role.createSystemRoles = async () => {
  const roles = [
    {
      name: '超级管理员',
      code: 'super_admin',
      description: '系统超级管理员，拥有所有权限',
      status: 1
    },
    {
      name: '部门管理员',
      code: 'dept_admin',
      description: '部门管理员，可管理本部门所有事务',
      status: 1
    },
    {
      name: '普通用户',
      code: 'normal_user',
      description: '普通用户，拥有基本权限',
      status: 1
    }
  ]

  for (const role of roles) {
    await Role.findOrCreate({
      where: { code: role.code },
      defaults: role
    })
  }
}

module.exports = Role 